<!--
File description:

This php script performs these main functionalities:
	1) Dynamically presents a formatted text box, the contents of which are individual changes performed by a user who crowdsourced a change.  The admin will then 
	have the option to inspect the specific change(s), and if the admin thinks the changes are good changes, he may approve the change.  Approving the change 
	allows the change to become permanent, afterwhich the log file for that change is deleted.  If the admin denies the change, the log file will be invoked, such that
	the pre-edited file will be restored, and the new version deleted.
	
	2) The second operation done here is changing where the program looks for OCR files.  This program assumes LAMP architecture, namely Apache on Linux.  The admin
	can change where to look for the OCR file directory.  The assumed layout of the OCR files is a three tier directory:
		OcrFileDirectory/BooksTitles/IndividualPages
	The 


	3) Allows a newly registered user to become a full-fledged member.  A user applies with a reason to become a crowdsourcer. Here is where the admin decides to accept or deny that 
	request


 -->

<?php
session_start(); 

//Check for logged in status, as well as admin status, if not, redirect to log in page.
if(!($_SESSION["logged_in"] == true && $_SESSION["permission"] == 2)){
    header("Location: sholem_login.php"); 
    exit;
}

//The following php file is needed for getters/setters of directories, and running remote server commands  
require_once "utility.php";
require_once "globals.php";

/* Start of Ben's code */
//if the user hits accept button
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['accept']))
{
// store variable passed through post.
        $email = $_POST['email'];
// Files saved into variables so if they change you only have to change thses variables. 
        $sFile = 'applicant.xml';
        $dFile = 'user.xml';

// load source and destinantion files.  
        $source = simplexml_load_file($sFile);
        $destination = simplexml_load_file($dFile);
// loop through all the users in the applicant file, to find the coresponding email that you want to approve.
        foreach ($source->xpath("/info/user[Email='".$email."']") as $user2)
        {
	    //store all the users information from the applicant file into variables so they can be stored into user.xml
            $newUser = $destination->addChild('user');
            $newUser->addChild('Email', $user2->Email);
            $newUser->addChild('First', $user2->First);
            $newUser->addChild('Last', $user2->Last);
            $newUser->addChild('Password', $user2->Password);
            $newUser->addChild('Reason', $user2->Reason);
            $newUser->addChild('Permission', $user2->Permission);
        }

// save the new applicant into user.xml
        $destination->saveXML($dFile);

// now to delet the user from applicant.xml
// create a new Dom documetn and load applicant 
        $doc = new DOMDocument;
        $doc->load("applicant.xml");
// set the xpath.
        $xpath2 = new DOMXPath($doc);
// loop through all the users in applicant until you find the user with the matching email.
       foreach($xpath2->query("/info/user[Email='".$email."']") as $user3)
       {
	// remove the users information.
        $user3->parentNode->removeChild($user3);
       }

// save the changed document to applicant.xml
       $doc->save('applicant.xml');

}

// If the user hits deny button.
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['deny']))
{
// save variable passed through the post. 
  $email = $_POST['email'];

// create a new Dom document and load applicant.xml
  $doc = new DOMDocument;
  $doc->load("applicant.xml");
// set the xpath
  $xpath = new DOMXPath($doc);
// loop through all the users in applicant until you find the user with the matching email.
  foreach($xpath->query("/info/user[Email='".$email."']") as $user)
  {
    // remove the users information.
    $user->parentNode->removeChild($user);

  }
  // Makes the outout  look neat so the xml file stays properly formatted.
  $doc->formatOutput = true;
// save the changed document to applicant.xml
  $doc->save('applicant.xml');

}

echo '<!DOCTYPE html>';
echo '<html>';
echo '<head>';
echo '<meta charset="UTF-8">';
echo '<!-- Latest compiled and minified CSS -->';
echo '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">';
echo '<!-- Latest compiled and minified JavaScript -->';
echo '<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>';
echo '<title>All Works of Sholem Aleichem - Admin</title>';
echo '<style>.top a {text-decoration: none;color: #fff;}
        .top a:hover {
                color: #c6c9c3;
        }
    </style>';
echo '</head>';
echo '<body>';

echo '<div class="col-md-12 row bg-primary text-center">';
echo '<div class="col-md-offset-3 col-md-6 text-center top">';
echo '<a href="searchSholem.cgi"><h1>All Works of Sholem Aleichem</h1></a>';
echo '<h4><a href="searchSholem.cgi">Search</a> | <a href="logout.php">Logout</a></h4>';
echo '</div>';
echo '</div>';
// Files saved into variables so if they change you only have to change thses variables. 
$file = "applicant.xml";
// load file
$xml = simplexml_load_file($file);


echo '<div class="container text-center">';
echo '<div class="row"><br></div>';
echo '<div class="row">';
// loops through applicant and displays all the applicant requests. 
        foreach($xml->children() as $user)
        {
// creates a form for each request
            echo '<form action="" method="POST" class="form-horizontal">';
// display the applicants email and reason they should be allowed to edit. 
		echo '<div class="form-group"><h4>';
                echo $user->Email . ": ";
                echo $user->Reason . " ";
		echo '</h4></div>';
// Two submit button one for deny request and one for accepting requests.
		echo '<div class="form-group">';
                echo '<input type="submit" class="btn btn-primary" name="accept" value="Accept">    ';
                echo '<input type="submit" class="btn btn-primary" name="deny" value="Deny"><br>';
		echo '</div>';
// Pass the users email as a hidden variables.
                echo '<input type="hidden" name="email" value="'.$user->Email.'">';
                echo '</form>';
            }

echo '</div>';
/*   End Ben's Code     */
?>



<!-----------------------------------------------------------------------------------------------------
Start of code by Tristan
----------------------------------------------------------------------------------------------------- -->

<?php

/*The follow block of code accesses our log files which hold the crowdsourced changes by the users. It prints individual
changes (diff) made to the admin.  The admin can approve or deny each change INDIVIDUALLY.  Either action will make a 
call to validate.php which handles the specific SVN commit (allow) or log file delete (deny).  Then validate.php
will return back to this page, admin.php.  With each admin accept/deny, that diff will go away.  Diff results are
presented with the most recent change being last (bottom of the page)
*/
echo "<br><h2>Recent User Edits: </h2>".$_GET['msg']."<br>";


	//Make a call to parseLogFiles, which is implemented in utility.php. Store the array of arrays of info about our logs
	// into $logs variable. For further info, see documentation in utitly.php, function parseLogFiles().  
    $logs = parseLogFiles();

    //Now we have an array of array of log info.  Each index of the 2d array holds a specific log file. The inner 
    //array hold particular info about that log file, index 0 = the user name, index 1 = the book directory name
    //index 2 = the page directory name, index 4 = the time the user made the submission
	for ($i = 0 ; $i < sizeof($logs); $i=$i+3){
	//Store the exact log file name into a variable for ease of use	
	$userChange = "/mounts/u-zon-d2/ugrad/mtlank2/HTML/499/logs/".$logs[$i][0]."~".$logs[$i][1]."~".$logs[$i][2]."~".$logs[$i][3]."~diff";  
    echo $logs[$i][0]." changed book# ".$logs[$i][1]." , page# ".$logs[$i][2]." on ".date("l jS \of F Y h:i:s A", $logs[$i][3])."<br>"; 

	 /* Now send all data about the diff log file, including the diff itself to the front end so that the admin can 
	 make a decision to approve the change or deny it.  In either case, we pass info about the particular log file
	 into validate.php via POST from invisible input types.  Essentially what is happening here is that we are automating
	 the changes the users made, and temporarily storing that log file data for each change into the front-end.  From
	 there, the admin will click deny or approve, which triggers validate.php. Validate.php draws data about a particular log file
	 from the data stored in the form below.  This is a variation of the post/redirect/get pattern, with this code block
	 starting the post.
	*/
	 echo 
		"
		<textarea rows='25' cols='75' name='editedText' readonly>
		".
		file_get_contents($userChange)  //Retreive the info from the specific diff log file, print to admin page 
		.
		"
		</textarea>
		<form action='validate.php' method='post'> 
		  <input type='hidden' name='time' value='".time()."' />
		  <input type='hidden' name='user' value='".$logs[$i][0]."'>
		  <input type='hidden' name='book' value='".$logs[$i][1]."'>
		  <input type='hidden' name='page' value='".$logs[$i][2]."'>
		  <input type='hidden' name='time' value='".$logs[$i][3]."'>
		  Press Accept to allow change.  Press Deny to revert the change.
		  <button name='commitOcrChange' type='submit' value='commitOcrChange'>Accept</button>
		  <button name='denyOcrChange' type='submit' value='denyOcrChange'>Deny</button>
		</form>
		<br><br><br><br><br><br>
		"; //Finished printing a single change for this loop iteration

}



?>

<?php
/*Admin changes path of Sholem OCR Files.  This code block is used so that the admin can change where the entire program
will look for its OCR files.  This functionality *REQUIRES* that the directory have a "books" subdirectory, and within
the book directory, there are individual pages.  In other words, a particular OCR file would be stored in a directory
of the pattern ocrFiles/book/page.txt

This functionality should be set only up to the ocrFiles directory.
*/
echo "<br><h2>New OCR File Path:</h2><h4>Set the Multilab absolute path location of the OCR files to be crowdsourced.  NOTE: The path should be set up to parent directory of the books you wish to crowdsource.  
Example: path/to/ocrFilesDirectory/book/page *IS NOT* the path you should set.  Instead, using the same example, the correct path to set would be: path/to/ocrFilesDirectory </h4>";
?>

<!--Make call to validate.php, which interprets the ocrFilesPath data passed to it via POST -->
<form action="validate.php" class="form-inline" method="post">
<div class="form-group">
Absolute Path (i.e use pwd command): <input type="text" class="form-control" name="ocrFilesPath"><br>
</div>
<input class="btn btn-primary" type="submit">
</form>
</div>

</body>
</html>
<!-----------------------------------------------------------------------------------------------------
End of code by Tristan
----------------------------------------------------------------------------------------------------- -->
